<template>
  <!-- 报价添加 -->
  <div class="contractInfo box">
    <el-divider content-position="left">{{
      $route.query.mode == "add" ? "添加报价" : "编辑报价"
    }}</el-divider>
    <div class="formBox">
      <el-form
        :model="form"
        :rules="rules"
        ref="addForm"
        label-width="auto"
        label-position="right"
      >
        <!-- <el-form-item label="报价单号" prop="quotesNumber" required style="width: 100%">
          <p>{{ form.quotesNumber }}</p>
        </el-form-item> -->
        <el-form-item label="客户" prop="customerId">
          <el-select
            v-model="form.customerId"
            @change="selectCustomerChange"
            placeholder="请选择客户"
            style="width: 100%"
            remote
            filterable
            remote-show-suffix
            :remote-method="queryCustomer"
            :loading="selectCustomerLoading"
            clearable
          >
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.customerName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报价名称" prop="quotesName">
          <el-input
            v-model="form.quotesName"
            clearable
            placeholder="请输入报价名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="付款方式">
          <el-input
            v-model="form.payDescription"
            clearable
            placeholder="请输入付款方式"
          ></el-input>
        </el-form-item>
        <el-form-item label="交货日期">
          <el-input
            v-model="form.deliveryTime"
            clearable
            placeholder="请输入天数"
            oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,0})?.*$/,'$1')"
            @blur="form.deliveryTime = $event.target.value"
          >
            <template #append>天之后</template>
          </el-input>
        </el-form-item>
        <el-form-item label="验收标准" style="width: 100%">
          <el-input
            v-model="form.checkRule"
            type="textarea"
            rows="3"
            clearable
            placeholder="请输入验收标准"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品列表" prop="products" style="width: 100%">
          <sc-form-table
            ref="table"
            v-model="form.products"
            :addTemplate="productsTemplate"
            drag-sort
            placeholder="暂无数据"
          >
            <el-table-column prop="productIds" label="产品名称" width="180">
              <template #default="scope">
                <!-- <el-select v-model="productsId" placeholder="请选择客户"
                  style="width: 100%" remote filterable remote-show-suffix :remote-method="queryProducts"
                  :loading="selectProductsLoading" clearable>
                  <el-option v-for="item in productsList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select> -->
                <sc-table-select
                  v-model="scope.row.productsData"
                  :apiObj="apiObj"
                  :table-width="700"
                  clearable
                  collapse-tags
                  collapse-tags-tooltip
                  :props="productsProps"
                  @change="productChange(scope.row)"
                >
                  <template #header="{ form, submit }">
                    <el-form :inline="true" :model="form">
                      <el-form-item>
                        <el-input
                          v-model="form.search"
                          placeholder="产品名称"
                        ></el-input>
                      </el-form-item>
                      <div>
                        <el-button type="primary" @click="addProduct"
                          >添加产品</el-button
                        >
                        <el-button type="primary" @click="submit"
                          >查询</el-button
                        >
                      </div>
                    </el-form>
                    <!-- <el-alert title="自定义FORM插糟 传递了form对象和提交方法" type="info" /> -->
                  </template>
                  <el-table-column
                    label="产品名称"
                    prop="name"
                    min-width="100"
                  ></el-table-column>
                  <el-table-column
                    label="规格型号"
                    prop="specification"
                    min-width="100"
                  ></el-table-column>
                  <el-table-column
                    label="产品单价"
                    prop="onePrice"
                    width="100"
                  ></el-table-column>
                  <el-table-column
                    label="产品单位"
                    prop="unitName"
                    width="100"
                  ></el-table-column>
                </sc-table-select>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="time" label="时间" width="180">
              <template #default="scope">
                <el-time-select v-model="scope.row.time"></el-time-select>
              </template>
            </el-table-column> -->
            <el-table-column
              label="规格型号"
              prop="specification"
              width="250"
            ></el-table-column>
            <el-table-column prop="onePrice" label="单价" width="180">
              <template #default="scope">
                <el-input-number
                  :precision="2"
                  v-model.number="scope.row.onePrice"
                  placeholder="请输入单价"
                  @change="changePrice(scope.row)"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="num" label="数量" width="180">
              <template #default="scope">
                <el-input-number
                  :precision="0"
                  v-model.number="scope.row.num"
                  placeholder="请输入数量"
                  @change="changePrice(scope.row)"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="总金额" width="180">
              <template #default="scope">
                <el-input v-model="scope.row.price" :disabled="true"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="unitName" label="单位" width="180">
              <template #default="scope">
                {{ scope.row.unitName }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="open" label="checked" width="85" align="center">
              <template #default="scope">
                <el-checkbox v-model="scope.row.checked"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="open" label="开关" width="80" align="center">
              <template #default="scope">
                <el-switch v-model="scope.row.open"></el-switch>
              </template>
            </el-table-column> -->
          </sc-form-table>
        </el-form-item>
        <el-form-item label="备注" prop="description" style="width: 100%">
          <el-input
            v-model="form.description"
            clearable
            rows="3"
            type="textarea"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="是否优惠" class="formRow">
          <el-switch
            v-model="form.isDiscount"
            :inactive-value="0"
            :active-value="1"
          />
          <el-input
            v-show="form.isDiscount == 1"
            v-model="form.discountMoney"
            placeholder="请输入优惠金额"
            clearable
            @change="countPrice"
          >
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item></el-form-item> -->
        <el-form-item label="总金额">
          <!-- <el-input
            v-model="form.discount"
            placeholder="请输入优惠金额"
            clearable
          ></el-input> -->
          <p>{{ form.price }}元</p>
        </el-form-item>
      </el-form>
      <!-- 审核流程项 -->
      <check-form-item
        ref="checkFormItem"
        @setCheckConfig="setCheckConfig"
        :field="this.form"
        :checkType="checkType"
        v-if="$route.query.mode == 'add'"
      ></check-form-item>
      <div class="button">
        <el-button type="primary" @click="save" :loading="isSaveing"
          >保 存</el-button
        >
        <el-button @click="cencel">取 消</el-button>
      </div>
    </div>

    <!-- 添加产品弹窗· -->
    <add-product
      ref="addProduct"
      @getProductData="getProductData"
    ></add-product>
  </div>
</template>
<script>
import checkFormItem from '@/components/checkProcess/checkFormItem.vue'
import addProduct from '../components/addProduct.vue'
export default {
  name: 'customerAdd',
  data () {
    return {
      checkType: 1,//工作流的类型
      isSaveing: false,
      //表单数据
      form: {
        recodeId: '',//跟进人id --登录时id
        departmentId: '',
        customerId: '',
        quotesNumber: '',//报价单号
        quotesName: '',//报价名称
        price: 0,//价格
        description: '',//描述
        // isDiscount: 0,//	是否优惠 0否 1是
        // discountMoney: '',//优惠金额
        payDescription: '',//付款方式描述
        deliveryTime: '',//交货日期
        checkRule: '',//验收标准
        exempt: '',//是否免审
        products: [], //产品list
        workflowJsonList: []
      },
      //产品模版
      productsTemplate: {
        id: '',
        num: '',
        onePrice: '',
        price: '',
        productsId: '',
        productsData: '',
        name: ''
      },
      productsProps: {
        label: 'name',
        value: 'id',
        keyword: "keyword"
      },
      searchValue: {
        search: ''
      },
      apiObj: this.$API.vendorProducts.selectVendorProductsList,
      customerList: [],
      selectCustomerLoading: false,
      selectProductsListLoding: false,
      productList: [],
      //验证规则
      rules: {
        quotesName: [
          { required: true, message: '请输入报价名称' }
        ],
        // price: [
        //   { required: true, message: '请输入价格' }
        // ],
        quoteTime: [
          { type: 'date', required: true, message: '请选择报价日期', trigger: 'change' }
        ],
        customerId: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
      }
    }
  },
  components: {
    checkFormItem,
    addProduct
  },
  mounted () {
    // this.getContractList()
    if (this.$route.query.mode == 'edit') {
      this.getQuoteById()
    }
    this.getCustomeList()
    // this.getPrductsList()
  },
  methods: {
    // 获取客户列表
    async getCustomeList (val) {
      this.selectCustomerLoading = true
      let param = {
        limit: 1000,
        page: 1,
        search: val,
        status: 1
      }
      let res = await this.$API.customer.getCustomers.get(param)
      this.selectCustomerLoading = false
      this.customerList = res.data
    },
    // 搜索客户
    queryCustomer (val) {
      this.getCustomeList(val)
    },
    queryProducts (val) {
      this.getPrductsList(val)
    },
    async getPrductsList (val) {
      this.selectPrductListLoading = true
      let param = {
        limit: 1000,
        page: 1,
        search: val
      }
      let res = await this.$API.vendorProducts.selectVendorProductsList.get(param)
      this.selectPrductListLoading = false
      this.productsList = res.data
    },
    selectCustomerChange (val) {
      if (val != '') {
        var customerName = this.customerList.find((item) => item.id === val).customerName
        let time = this.$TOOL.dateFormat(new Date(), 'yyyy-MM-dd')
        var str = "【" + customerName + "】-" + time
        this.form.quotesName = str
      } else {
        this.form.quotesName = ''
      }
    },
    changePrice (row) {
      row.price = (row.onePrice * row.num).toFixed(2)
      this.form.price = 0
      this.form.products.forEach(element => {
        this.form.price = +this.form.price + (+element.price)
      })
      console.log(this.form)
    },
    productChange (row) {
      console.log(row)
      row.specification = row.productsData.specification
      row.onePrice = row.productsData.onePrice
      row.unitName = row.productsData.unitName
      row.unit = row.productsData.unit
      row.vendorId = row.productsData.vendorId
      row.productsId = row.productsData.id
    },

    // 跟根据优惠金额计算总金额
    countPrice (val) {
      this.form.price = 0
      this.form.products.forEach(element => {
        this.form.price = +this.form.price + (+element.price)
      })
      this.form.price = this.form.price - val
      console.log(this.form)
    },

    // 获取合同列表
    async getContractList (val) {
      this.selectContractLoading = true
      let param = {
        limit: 1000,
        page: 1,
        search: val,
        status: 1
      }
      let res = await this.$API.contract.getContracts.get(param)
      this.selectContractLoading = false
      this.contractList = res.data
    },

    // 搜索合同
    queryContract (val) {
      this.getContractList(val)
    },

    // 审批流配置
    setCheckConfig (list, exempt) {
      this.form.workflowJsonList = list
      this.form.exempt = exempt
    },

    // 获取报价信息
    async getQuoteById () {
      let { data } = await this.$API.contract.quoteManagement.getQuoteDetailById.post({ id: this.$route.query.id })
      this.form = data
    },

    // 添加产品
    addProduct () {
      this.$refs.addProduct.open()
    },

    // 产品数据返回
    getProductData (data) {
      this.form.products.forEach(item => {
        if (item.productsData == '') {
          item.productsData = {
            ...data,
            unit: data.unit,
            unitName: data.unitName,
            productsId: data.id,
          }
          item.onePrice = data.onePrice
          item.name = data.name
          item.unit = data.unit
          item.unitName = data.unitName
          item.specification = data.specification
          item.productsId = data.id
        }
      })
    },

    async save () {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true
          let userInfo = this.$TOOL.data.get('USER_INFO')
          this.form.departmentId = userInfo.departmentId
          this.form.recodeId = userInfo.userId
          if (this.form.products.length === 0) {
            this.$message.error("请选择报价的产品列表")
            this.isSaveing = false
            return
          }
          var productsStatus = false
          this.form.products.forEach(e => {
            if (e.price == null || e.price == '') {
              productsStatus = true
            }
          })
          if (productsStatus == true) {
            this.$message.error("产品无总金额，请添加单价或者数量")
            this.isSaveing = false
            return
          }
          console.log(this.form)
          // this.form.price = 0
          // this.form.products.forEach(element => {
          //   this.form.price = +this.form.price + (+element.price)
          // })

          // if (this.form.isDiscount == 1) this.form.price = +this.form.price - (+this.form.discountMoney)

          let res = null
          let mode = this.$route.query.mode
          if (mode == 'add') {
            res = await this.$API.contract.quoteManagement.addQuote.post(this.form)
          } else if (mode == 'edit') {
            res = await this.$API.contract.quoteManagement.updateQuote.post(this.form)
          }
          this.isSaveing = false
          if (res.code == 200) {
            this.$emit('success', this.form, this.mode)
            this.closeSelectedTag(this.$route)
            this.$router.push({
              path: '/customer/quoteManagement'
            })
            this.$message.success("操作成功")
          }
        }
      })
    },

    // 取消客户添加
    cencel () {
      this.closeSelectedTag(this.$route)
      this.$router.push({
        path: '/customer/quoteManagement'
      })
    },
    //关闭tag
    closeSelectedTag (tag) {
      this.$store.commit("removeViewTags", tag)
      this.$store.commit("removeIframeList", tag)
      this.$store.commit("removeKeepLive", tag.name)
    },
  }

}

</script>
<style lang='scss' scoped>
.box {
  margin: 10px;
}

.formBox {
  padding: 30px;
  background: #fff;

  .el-form {
    width: 100%;
  }
}
.formRow {
  :deep(.el-form-item__content) {
    flex-wrap: nowrap;
    .el-input {
      width: 50%;
      margin-left: 20px;
    }
  }
}

.button {
  margin-top: 50px;
  padding-left: 60px;
}

:deep(.el-divider__text) {
  padding: 0 10px;
  font-size: 18px;
  // font-weight: 600;
  background-color: #f6f8f9;
}
</style>